//
//  ZJRegisterViewController.m
//  BreadTravel
//
//  Created by 张健 on 16/1/4.
//  Copyright © 2016年 蓝鸥科技. All rights reserved.
//

#import "ZJRegisterViewController.h"
#import "DataBase.h"
@interface ZJRegisterViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property(nonatomic,strong)UIImageView *headImageView;
@property(nonatomic,strong)UILabel *nameLabel;
@property(nonatomic,strong)UILabel *emailLabel;
@property(nonatomic,strong)UILabel *password;
@property(nonatomic,strong)UILabel *rePassword;

@property(nonatomic,strong)UITextField *tf_name;
@property(nonatomic,strong)UITextField *tf_email;
@property(nonatomic,strong)UITextField *tf_password;
@property(nonatomic,strong)UITextField *tf_rePassword;

@property(nonatomic,strong)NSData *data;

@end

@implementation ZJRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.tabBarController.tabBar.hidden = YES;
    [[DataBase shareDataBase]createUserTable];
    
//    [[DataBase shareDataBase]dropTable];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(15, 20+10, 20, 20);
    [backButton addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [backButton setBackgroundImage:[UIImage imageNamed:@"add_new_poi_back_btn"] forState:UIControlStateNormal];
    [self.view addSubview:backButton];
    
    self.headImageView = [[UIImageView alloc]init];
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.cornerRadius = 40;
    self.headImageView.userInteractionEnabled = YES;
//    self.headImageView.backgroundColor = [UIColor grayColor];
    self.headImageView.image = [UIImage imageNamed:@"iconfont-yonghu"];
    [self.view addSubview:self.headImageView];
    [self.headImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(80);
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(100);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.headImageView addGestureRecognizer:tap];
    
    self.nameLabel = [[UILabel alloc]init];
    self.nameLabel.text = @"+86";
    [self.view addSubview:self.nameLabel];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(60);
        make.top.equalTo(self.headImageView.mas_bottom).offset(45);
        make.width.mas_equalTo(40);
    }];
    
    self.tf_name = [[UITextField alloc]init];
    [self.view addSubview:self.tf_name];
    [self.tf_name mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.nameLabel);
        make.left.equalTo(self.nameLabel.mas_right);
        make.right.mas_equalTo(-120);
    }];
    
    UIView *aline = [[UIView alloc]init];
    aline.backgroundColor = [UIColor grayColor];
    [self.view addSubview:aline];
    [aline mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.tf_name.mas_bottom);
        make.width.equalTo(self.tf_name);
        make.height.mas_equalTo(1);
        make.left.equalTo(self.tf_name);
    }];
    
    UIButton *yanzhengButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [yanzhengButton setTitle:@"确认发送" forState:UIControlStateNormal];
    [yanzhengButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [yanzhengButton addTarget:self action:@selector(yanzhengButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:yanzhengButton];
    [yanzhengButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.tf_name.mas_right);
        make.top.equalTo(self.tf_name);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(20);
    }];
    
    self.tf_password = [[UITextField alloc]init];
    self.tf_password.placeholder = @"验证码";
    [self.view addSubview:self.tf_password];
    [self.tf_password mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.tf_name.mas_bottom).offset(20);
        make.left.equalTo(self.tf_name);
        make.right.equalTo(self.tf_name);
    }];
    
    UIView *bline = [[UIView alloc]init];
    bline.backgroundColor = [UIColor grayColor];
    [self.view addSubview:bline];
    [bline mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.tf_password.mas_bottom);
        make.width.equalTo(self.tf_name);
        make.height.mas_equalTo(1);
        make.left.equalTo(self.tf_name);
    }];
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"完成" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(finishButton) forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundColor:[UIColor blueColor]];
    [self.view addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.tf_password.mas_bottom).offset(40);
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.tf_password);
        make.right.equalTo(self.tf_password);
        make.height.mas_equalTo(50);
    }];
    
    UILabel *aLabel = [[UILabel alloc]init];
    aLabel.text = @"点击'完成'按钮,代表您已阅读并同意";
    aLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:aLabel];
    [aLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(button.mas_bottom).offset(60);
        make.centerX.equalTo(self.view).offset(-50);
        make.height.mas_equalTo(20);
    }];
    
    UILabel *bLabel = [[UILabel alloc]init];
    bLabel.text = @"    面包协议";
    bLabel.textColor = [UIColor colorWithRed:0.51 green:0.7 blue:0.34 alpha:1];
    bLabel.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:bLabel];
    [bLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(aLabel);
        make.left.equalTo(aLabel.mas_right);
        make.width.mas_equalTo(70);
    }];
}

- (void)yanzhengButton{
    
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.tf_name.text
                                   zone:@"86"
                       customIdentifier:nil
                                 result:^(NSError *error)
     {
         
         if (!error)
         {
             if (self.tf_name.text.length == 11) {
                 [self showAlert:@"验证码发送成功"];
             }
             [self showAlert:@"输入有误,请重新输入"];
         }
         else
         {
             
                          NSString *messageStr = [NSString stringWithFormat:@"%zidescription",error.code];
                          UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"codesenderrtitle", nil)
                                                                          message:NSLocalizedString(messageStr, nil)
                                                                         delegate:self
                                                                cancelButtonTitle:NSLocalizedString(@"sure", nil)
                                                                otherButtonTitles:nil, nil];
                          [alert show];
             [self showAlert:@"请输入号码"];
         }
         
     }];
    
}

//点击头像
- (void)tapAction:(UITapGestureRecognizer *)tap{
    [[NSUserDefaults standardUserDefaults]setObject:@"head" forKey:@"who"];
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing = YES;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:^{
        
    }];
}

//完成按钮
- (void)finishButton{
    
    [SMSSDK commitVerificationCode:self.tf_password.text phoneNumber:self.tf_name.text zone:@"86" result:^(NSError *error) {
        
        if (!error) {
            
            
            NSString *name = self.tf_name.text;
            NSString *password = @"1234";
            [self showAlert:@"默认密码为1234"];
            NSMutableArray *array = [[DataBase shareDataBase]selectUserData:name];
            
            if (array.count == 0) {
                //记录谁登陆的和插入数据
                [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"state"];
                [[NSUserDefaults standardUserDefaults]setObject:self.tf_name.text forKey:@"user"];
                
                [[DataBase shareDataBase]insertUser:name password:password headImage:self.data];
                [self dismissViewControllerAnimated:YES completion:^{
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [self dismissViewControllerAnimated:YES completion:^{
                            
                        }];
                    });
                }];
            }else{
                
                [self showAlert:@"用户名已注册"];
            }
            
            NSLog(@"成功");
            
        }
        else
        {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入正确的验证码" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertC animated:YES completion:^{
                
                
            }];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
                [self.navigationController dismissViewControllerAnimated:YES completion:^{
                    
                    
                }];
                
            }];
            
            [alertC addAction:action];
        }
        
        
    }];
  
}


//封装alert,简化代码
- (void)showAlert:(NSString *)message{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        });
    }];
}

//返回按钮
- (void)buttonAction{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//到系统相册
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    self.headImageView.image = image;
    
    self.data = UIImagePNGRepresentation(image);
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
